<template>
    <div class="post-item">
        <div class="post-header">
            <img :src="safeAuthor.avatar" alt="头像" class="user-avatar" />
            <div class="user-info">
                <div class="username">{{ safeAuthor.nickname }}</div>
                <div class="post-meta">
                    <span class="time">{{ formatTime(post.created_at) }}</span>
                </div>
            </div>
            <div class="post-actions">
                <el-dropdown v-if="isOwner" trigger="click" @command="handlePostCommand">
                    <el-button text>
                        <el-icon>
                            <More />
                        </el-icon>
                    </el-button>
                    <template #dropdown>
                        <el-dropdown-menu>
                            <el-dropdown-item command="edit">编辑</el-dropdown-item>
                            <el-dropdown-item command="delete" style="color: #ff4d4f;">删除</el-dropdown-item>
                        </el-dropdown-menu>
                    </template>
                </el-dropdown>
            </div>
        </div>

        <div class="post-content">
            {{ post.content }}
        </div>

        <div v-if="imageList.length > 0" class="post-images" :class="`image-count-${imageList.length}`">
            <img v-for="(image, index) in imageList" :key="index" :src="image" :alt="`图片${index + 1}`"
                @click="previewImages(index)" class="post-image" loading="lazy" />
        </div>

        <div class="post-stats">
            <span class="likes">{{ post.like_count }} 赞</span>
            <span class="comments">{{ post.comment_count }} 评论</span>
        </div>

        <div class="post-actions-bar">
            <button @click="handleLike" :class="['action-btn', 'like-btn', { liked: post.is_liked }]">
                <el-icon>
                    <Goods />
                </el-icon>
                {{ post.is_liked ? '已赞' : '赞' }}
            </button>
            <button class="action-btn comment-btn" @click="toggleComment">
                <el-icon>
                    <ChatDotRound />
                </el-icon>
                评论
            </button>
        </div>

        <!-- 评论区域 -->
        <div v-if="showComment" class="comment-section">
            <!-- 评论输入框 -->
            <div class="comment-input">
                <img :src="userStore.userInfo.avatar || '/default-avatar.png'" alt="头像" class="comment-avatar" />
                <div class="input-wrapper">
                    <el-input v-model="commentText" placeholder="写评论..." size="small" @keyup.enter="submitComment"
                        :maxlength="200" show-word-limit />
                    <el-button type="primary" size="small" @click="submitComment" :disabled="!commentText.trim()"
                        class="submit-btn">
                        发表
                    </el-button>
                </div>
            </div>

            <!-- 评论列表 -->
            <div v-if="comments.length > 0" class="comments-list">
                <div v-for="comment in comments" :key="comment.comment_id" class="comment-item">
                    <img :src="comment.commenter?.avatar || '/default-avatar.png'" alt="头像" class="comment-avatar" />
                    <div class="comment-content">
                        <div class="comment-header">
                            <span class="comment-author">{{ comment.commenter?.nickname || '匿名用户' }}</span>
                            <span class="comment-time">{{ formatTime(comment.created_at) }}</span>
                            <span class="comment-actions">
                                <span class="reply-btn" @click="toggleReply(comment)">
                                    回复
                                </span>
                                <span v-if="comment.user_id === userStore.userInfo.user_id" class="delete-btn"
                                    @click="deleteComment(comment.comment_id)">
                                    删除
                                </span>
                            </span>
                        </div>
                        <div class="comment-text">{{ comment.content }}</div>

                        <!-- 回复输入框 -->
                        <div v-if="activeReplyComment === comment.comment_id" class="reply-input">
                            <img :src="userStore.userInfo.avatar || '/default-avatar.png'" alt="头像"
                                class="comment-avatar" />
                            <div class="input-wrapper">
                                <el-input v-model="replyText" :placeholder="`回复 ${comment.commenter?.nickname}...`"
                                    size="small" @keyup.enter="submitReply(comment)" :maxlength="200" show-word-limit />
                                <el-button type="primary" size="small" @click="submitReply(comment)"
                                    :disabled="!replyText.trim()" class="submit-btn">
                                    回复
                                </el-button>
                            </div>
                        </div>

                        <!-- 回复列表 -->
                        <div v-if="comment.replies && comment.replies.length > 0" class="replies-list">
                            <div v-for="reply in comment.replies" :key="reply.comment_id" class="reply-item">
                                <img :src="reply.commenter?.avatar || '/default-avatar.png'" alt="头像"
                                    class="comment-avatar" />
                                <div class="reply-content">
                                    <div class="reply-header">
                                        <span class="reply-author">{{ reply.commenter?.nickname || '匿名用户' }}</span>
                                        <span class="reply-time">{{ formatTime(reply.created_at) }}</span>
                                        <span v-if="reply.user_id === userStore.userInfo.user_id" class="delete-btn"
                                            @click="deleteComment(reply.comment_id)">
                                            删除
                                        </span>
                                    </div>
                                    <div class="reply-text">
                                        <span class="reply-to">回复{{ safeAuthor.nickname || '用户' }}</span>
                                        {{ reply.content }}
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- 加载更多回复 -->
                        <div v-if="comment.hasMoreReplies && !comment.loadingReplies" class="load-more-replies">
                            <el-button text size="small" @click="loadMoreReplies(comment)">
                                加载更多回复
                            </el-button>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 空状态 -->
            <div v-else class="no-comments">
                暂无评论
            </div>
        </div>

        <!-- 图片预览对话框 -->
        <el-dialog v-model="imagePreviewVisible" :title="`图片 ${currentImageIndex + 1} / ${imageList.length}`"
            width="80%" top="5vh" align-center>
            <div class="image-preview-container">
                <img :src="currentImageUrl" alt="预览图片" class="preview-image" />
                <div class="preview-actions">
                    <el-button @click="prevImage" :disabled="currentImageIndex === 0">
                        <el-icon>
                            <ArrowLeft />
                        </el-icon>
                        上一张
                    </el-button>
                    <el-button @click="nextImage" :disabled="currentImageIndex === imageList.length - 1">
                        下一张
                        <el-icon>
                            <ArrowRight />
                        </el-icon>
                    </el-button>
                    <el-button type="primary" @click="imagePreviewVisible = false">
                        关闭
                    </el-button>
                </div>
            </div>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, computed, onUnmounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Goods, ChatDotRound, More, ArrowLeft, ArrowRight } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'
import { usePostsStore } from '@/stores/posts'

const props = defineProps({
    post: {
        type: Object,
        required: true
    }
})

const emit = defineEmits(['update', 'delete'])

const userStore = useUserStore()
const postsStore = usePostsStore()

const showComment = ref(false)
const commentText = ref('')
const replyText = ref('')
const comments = ref([])
const commentsLoaded = ref(false)
const loadingComments = ref(false)
const activeReplyComment = ref(null)

// 图片预览相关
const imagePreviewVisible = ref(false)
const currentImageIndex = ref(0)
const currentImageUrl = computed(() => imageList.value[currentImageIndex.value])

// 添加清理标志
let isComponentMounted = true

// 监听评论区域的显示/隐藏
watch(showComment, (newVal) => {
    if (newVal && !commentsLoaded.value) {
        loadComments()
    }
})

const isOwner = computed(() => {
    return props.post.user_id === userStore.userInfo.user_id
})

const imageList = computed(() => {
    if (!props.post.images || props.post.images === 'null' || props.post.images === null) {
        return []
    }

    try {
        // 如果已经是数组，直接返回
        if (Array.isArray(props.post.images)) {
            return props.post.images.filter(img => img && img.trim())
        }

        // 如果是字符串，按逗号分割
        if (typeof props.post.images === 'string') {
            const images = props.post.images.split(',').filter(img => img && img.trim())
            return images.map(img => img.trim())
        }

        return []
    } catch (error) {
        console.error('图片数据解析错误:', error)
        return []
    }
})

// 确保 author 有默认值
const safeAuthor = computed(() => {
    return props.post.author || {
        avatar: '/default-avatar.png',
        nickname: '匿名用户',
        user_id: 0
    }
})

// 切换回复输入框
const toggleReply = (comment) => {
    if (activeReplyComment.value === comment.comment_id) {
        activeReplyComment.value = null
        replyText.value = ''
    } else {
        activeReplyComment.value = comment.comment_id
        replyText.value = ''

        // 如果还没有加载过回复，则加载回复
        if (!comment.replies) {
            loadReplies(comment)
        }
    }
}

// 加载评论回复
const loadReplies = async (comment, loadMore = false) => {
    if (!isComponentMounted) return

    try {
        if (!loadMore) {
            comment.loadingReplies = true
        }

        const page = loadMore ? (comment.replyPage || 1) + 1 : 1
        const result = await postsStore.getCommentRepliesAction(comment.comment_id, {
            page: page,
            pageSize: 5
        })

        if (result && result.code === 0) {
            const replies = result.data.list || result.data || []

            if (loadMore) {
                comment.replies = [...(comment.replies || []), ...replies]
                comment.replyPage = page
            } else {
                comment.replies = replies
                comment.replyPage = 1
            }

            // 检查是否还有更多回复
            comment.hasMoreReplies = replies.length === 5 // 假设每页5条
        }
    } catch (error) {
        console.error('加载回复失败:', error)
        ElMessage.error('加载回复失败')
    } finally {
        comment.loadingReplies = false
    }
}

// 加载更多回复
const loadMoreReplies = async (comment) => {
    await loadReplies(comment, true)
}

// 时间格式化函数，处理不同的时间格式
const formatTime = (timeStr) => {
    if (!timeStr || timeStr === 'null') return '未知时间'

    try {

        let date
        if (timeStr.includes('T')) {
            // ISO 格式
            date = new Date(timeStr)
        } else {
            // 普通日期时间格式
            date = new Date(timeStr.replace(' ', 'T'))
        }

        const now = new Date()
        const diff = now - date

        const minute = 60 * 1000
        const hour = 60 * minute
        const day = 24 * hour

        if (diff < minute) {
            return '刚刚'
        } else if (diff < hour) {
            return Math.floor(diff / minute) + '分钟前'
        } else if (diff < day) {
            return Math.floor(diff / hour) + '小时前'
        } else if (diff < 7 * day) {
            return Math.floor(diff / day) + '天前'
        } else {
            return date.toLocaleDateString()
        }
    } catch (error) {
        console.error('时间格式化错误:', error, timeStr)
        return '未知时间'
    }
}

const handleLike = async () => {
    if (!isComponentMounted) return

    try {
        if (props.post.is_liked) {
            await postsStore.unlike(props.post.post_id)
        } else {
            await postsStore.like(props.post.post_id)
        }
    } catch (error) {
        console.error('操作失败:', error)
        ElMessage.error('操作失败：' + error.message)
    }
}

const handlePostCommand = async (command) => {
    if (!isComponentMounted) return

    switch (command) {
        case 'edit':
            emit('update', props.post)
            break
        case 'delete':
            try {
                await ElMessageBox.confirm('确定要删除这条动态吗？', '提示', {
                    type: 'warning',
                    confirmButtonText: '确定',
                    cancelButtonText: '取消'
                })
                await postsStore.removePost(props.post.post_id)
                ElMessage.success('删除成功')
                emit('delete', props.post.post_id)
            } catch (error) {
                if (error !== 'cancel') {
                    ElMessage.error('删除失败：' + error.message)
                }
            }
            break
    }
}

const toggleComment = () => {
    if (!isComponentMounted) return
    showComment.value = !showComment.value
}

// 图片预览功能
const previewImages = (index) => {
    if (!isComponentMounted) return
    currentImageIndex.value = index
    imagePreviewVisible.value = true
}

const prevImage = () => {
    if (currentImageIndex.value > 0) {
        currentImageIndex.value--
    }
}

const nextImage = () => {
    if (currentImageIndex.value < imageList.value.length - 1) {
        currentImageIndex.value++
    }
}

// 加载评论
const loadComments = async () => {
    if (!isComponentMounted) return

    try {
        loadingComments.value = true
        const result = await postsStore.getPostCommentsAction(props.post.post_id, {
            page: 1,
            pageSize: 100
        })

        if (result && result.code === 0) {
            const commentsData = result.data.list || result.data || []

            // 初始化回复相关字段
            comments.value = commentsData.map(comment => ({
                ...comment,
                replies: null, // 初始化为 null，表示还未加载
                hasMoreReplies: false,
                loadingReplies: false,
                replyPage: 1
            }))
        }
        commentsLoaded.value = true
    } catch (error) {
        console.error('加载评论失败:', error)
        ElMessage.error('加载评论失败')
    } finally {
        loadingComments.value = false
    }
}

// 提交评论（顶级评论）
const submitComment = async () => {
    if (!isComponentMounted) return
    if (!commentText.value.trim()) return

    try {
        const commentData = {
            post_id: parseInt(props.post.post_id, 10),
            content: commentText.value.trim(),
            parent_id: null // 明确设置为 null 表示顶级评论
        }
        const result = await postsStore.addCommentAction(commentData)
        if (result && result.code === 0) {
            ElMessage.success('评论成功')
            commentText.value = ''

            // 重新加载评论列表
            await loadComments()

            // 刷新帖子数据更新评论数
            emit('refresh')
        } else {
            throw new Error(result?.msg || '评论失败')
        }
    } catch (error) {
        console.error('评论失败:', error)
        ElMessage.error('评论失败：' + error.message)
    }
}

// 提交回复
const submitReply = async (parentComment) => {
    if (!isComponentMounted) return
    if (!replyText.value.trim()) return

    try {
        const commentData = {
            post_id: parseInt(props.post.post_id, 10),
            content: replyText.value.trim(),
            parent_id: parentComment.comment_id // 设置父评论ID
        }
        const result = await postsStore.addCommentAction(commentData)
        if (result && result.code === 0) {
            ElMessage.success('回复成功')
            replyText.value = ''
            activeReplyComment.value = null

            // 重新加载该评论的回复
            await loadReplies(parentComment)
        } else {
            throw new Error(result?.msg || '回复失败')
        }
    } catch (error) {
        console.error('回复失败:', error)
        ElMessage.error('回复失败：' + error.message)
    }
}

// 删除评论（同时处理顶级评论和回复）
const deleteComment = async (commentId) => {
    if (!isComponentMounted) return

    try {
        await ElMessageBox.confirm('确定要删除这条评论吗？', '提示', {
            type: 'warning',
            confirmButtonText: '确定',
            cancelButtonText: '取消'
        })

        await postsStore.deleteCommentAction(commentId)
        ElMessage.success('删除成功')

        // 从评论列表中移除
        let commentRemoved = false

        // 先检查顶级评论
        comments.value = comments.value.filter(comment => {
            if (comment.comment_id === commentId) {
                commentRemoved = true
                return false
            }
            return true
        })

        // 如果不是顶级评论，检查所有评论的回复
        if (!commentRemoved) {
            comments.value.forEach(comment => {
                if (comment.replies) {
                    comment.replies = comment.replies.filter(reply => reply.comment_id !== commentId)
                }
            })
        }

        // 刷新帖子数据更新评论数
        emit('refresh')
    } catch (error) {
        if (error !== 'cancel') {
            ElMessage.error('删除失败：' + error.message)
        }
    }
}

onUnmounted(() => {
    isComponentMounted = false
})
</script>

<style scoped>
.post-item {
    background: white;
    border-radius: 8px;
    padding: 16px;
    margin-bottom: 16px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.post-header {
    display: flex;
    align-items: flex-start;
    margin-bottom: 12px;
}

.user-avatar {
    width: 48px;
    height: 48px;
    border-radius: 50%;
    margin-right: 16px;
    border: 3px solid #e4e7ed;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.user-info {
    flex: 1;
}

.username {
    font-weight: 600;
    color: #333;
    margin-bottom: 2px;
}

.post-meta {
    font-size: 12px;
    color: #999;
}

.post-meta .time {
    margin-right: 8px;
}

.post-actions {
    margin-left: auto;
}

.post-content {
    margin-bottom: 12px;
    line-height: 1.5;
    color: #333;
    white-space: pre-wrap;
    word-break: break-word;
}

.post-images {
    margin-bottom: 12px;
    border-radius: 6px;
    overflow: hidden;
    width: 200px;
    height: 200px;
}

.post-images.image-count-1 {
    max-width: 400px;
}

.post-images.image-count-2 {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 4px;
}

.post-images.image-count-3,
.post-images.image-count-4,
.post-images.image-count-5,
.post-images.image-count-6,
.post-images.image-count-7,
.post-images.image-count-8,
.post-images.image-count-9 {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 4px;
}

.post-image {
    width: 100%;
    height: 100%;
    object-fit: cover;
    cursor: pointer;
    background: #f5f7fa;
    transition: transform 0.2s;
}

.post-image:hover {
    transform: scale(1.02);
}

.post-stats {
    padding: 8px 0;
    border-bottom: 1px solid #f0f0f0;
    font-size: 12px;
    color: #666;
}

.post-stats .likes {
    margin-right: 16px;
}

.post-actions-bar {
    display: flex;
    padding: 8px 0;
}

.action-btn {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 4px;
    background: none;
    border: none;
    padding: 8px;
    cursor: pointer;
    color: #666;
    font-size: 14px;
    border-radius: 4px;
    transition: all 0.2s;
}

.action-btn:hover {
    background: #f5f7fa;
}

.like-btn.liked {
    color: #1890ff;
}

.comment-section {
    margin-top: 12px;
    padding-top: 12px;
    border-top: 1px solid #f0f0f0;
}

.comment-input {
    display: flex;
    align-items: flex-start;
    gap: 8px;
    margin-bottom: 16px;
}

.comment-avatar {
    width: 32px;
    height: 32px;
    border-radius: 50%;
    object-fit: cover;
}

.input-wrapper {
    flex: 1;
    display: flex;
    gap: 8px;
}

.submit-btn {
    white-space: nowrap;
}

.comments-list {
    margin-bottom: 12px;
    max-height: 300px;
    overflow-y: auto;
    border: 1px solid #f0f0f0;
    border-radius: 6px;
    padding: 8px;
}

.comment-item {
    display: flex;
    gap: 8px;
    margin-bottom: 12px;
    padding: 8px;
    border-radius: 6px;
    background: #f8f9fa;
}

.comment-item:last-child {
    margin-bottom: 0;
}

.comment-content {
    flex: 1;
}

.comment-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 4px;
}

.comment-author {
    font-weight: 600;
    font-size: 13px;
    color: #333;
}

.comment-time {
    font-size: 11px;
    color: #999;
}

.delete-btn {
    font-size: 11px;
    color: #ff4d4f;
    cursor: pointer;
}

.delete-btn:hover {
    text-decoration: underline;
}

.comment-text {
    font-size: 14px;
    line-height: 1.4;
    color: #333;
    word-break: break-word;
}

.no-comments {
    text-align: center;
    padding: 20px;
    color: #999;
    font-size: 14px;
}

/* 图片预览样式 */
.image-preview-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 16px;
}

.preview-image {
    max-width: 100%;
    max-height: 70vh;
    object-fit: contain;
    border-radius: 8px;
}

.preview-actions {
    display: flex;
    gap: 12px;
    justify-content: center;
}

.comment-actions {
    display: flex;
    gap: 12px;
}

.reply-btn {
    font-size: 11px;
    color: #1890ff;
    cursor: pointer;
}

.reply-btn:hover {
    text-decoration: underline;
}

.reply-input {
    display: flex;
    align-items: flex-start;
    gap: 8px;
    margin-top: 8px;
    padding: 8px;
    background: #f8f9fa;
    border-radius: 6px;
}

.replies-list {
    margin-top: 8px;
    padding-left: 16px;
    border-left: 2px solid #e9ecef;
}

.reply-item {
    display: flex;
    gap: 8px;
    margin-bottom: 8px;
    padding: 8px;
    border-radius: 6px;
    background: #f8f9fa;
}

.reply-item:last-child {
    margin-bottom: 0;
}

.reply-content {
    flex: 1;
}

.reply-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 4px;
}

.reply-author {
    font-weight: 600;
    font-size: 12px;
    color: #333;
}

.reply-time {
    font-size: 10px;
    color: #999;
}

.reply-text {
    font-size: 13px;
    line-height: 1.4;
    color: #333;
    word-break: break-word;
}

.reply-to {
    color: #1890ff;
    margin-right: 4px;
}

.load-more-replies {
    text-align: center;
    margin-top: 8px;
}
</style>